package com.nisure.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.http.HttpRequest;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baidu.drapi.autosdk.core.ResHeader;
import com.baidu.drapi.autosdk.core.ResHeaderUtil;
import com.baidu.drapi.autosdk.exception.ApiException;
import com.baidu.drapi.autosdk.sms.service.GetCampaignRequest;
import com.baidu.drapi.autosdk.sms.service.GetCampaignResponse;
import com.nisure.AutoKeywordApplication;
import com.nisure.common.CommonData;
import com.nisure.common.CreateJsonObject;
import com.nisure.common.GetHttpJsonobject;
import com.nisure.common.R;
import com.nisure.entity.AccountEntity;
import com.nisure.info.CampaignTypeInfo;
import com.nisure.info.KeywordTypeInfo;
import com.nisure.service.AccountService;
import com.nisure.service.AdgroupService;
import com.nisure.service.CampaignService;
import com.nisure.service.KeywordService;
import com.nisure.type.CampaignType;

@RestController
public class IndexController extends HttpServlet {

	private static final Logger logger = LoggerFactory
			.getLogger(AutoKeywordApplication.class);
	@Autowired
	private AccountController accountController;
	@Autowired
	private KeywordController keywordController;
	@Autowired
	private CampaignController campaignController;
	@Autowired
	private CampaignService campaignService;
	@Autowired
	private CreateJsonObject createJsonObject;
	@Autowired
	private GetHttpJsonobject getHttpJsonobject;
	@Autowired
	private AdgroupController adgroupController;
	@Autowired
	private AccountService accountService;
	@Autowired
	private AdgroupService adgroupService;
	@Autowired
	private KeywordService keywordService;

	private static final SimpleDateFormat sdf = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");

	public ModelAndView error() {
		ModelAndView mav = new ModelAndView("page/error.html");
		return mav;

	}

	@RequestMapping("/")
	public ModelAndView index(@RequestParam Map<String, Object> params,
			HttpServletRequest request) {
		Logger logger = LoggerFactory.getLogger(getClass());
		String authCode = (String) params.get("code");
		String url = CommonData.uri + "?client_id=" + CommonData.clientId
				+ "&client_secret=" + CommonData.clientSecret + "&grant_type="
				+ CommonData.grantType + "&code=" + authCode + "&redirect_uri="
				+ CommonData.redirect_uri;
		JSONObject jsonObject = new JSONObject();
		GetHttpJsonobject gethttpjson = new GetHttpJsonobject();
		jsonObject = gethttpjson.httpsRequest(url, "POST", null);
		logger.info(jsonObject.toJSONString());
		String userName = jsonObject.getString("username");
		String refreshToken = jsonObject.getString("refresh_token");
		List<AccountEntity> account = accountController.queryAccount(userName);

		long userId = accountController.handleAccount(jsonObject);

		if (userId > 0) {
			// 保存userId到session
			HttpSession session = request.getSession();
			session.setAttribute("userId", userId);
			session.setAttribute("userName", userName);
			ModelAndView mav = new ModelAndView("page/landing.html");
			return mav;
		} else {
			return null;
		}

	}

	@RequestMapping("tests")
	public List<KeywordTypeInfo> test4(
			@RequestParam Map<String, Object> params, HttpServletRequest request) {
		Date start = new Date();
		logger.info("start schedule" + sdf.format(start));
		List<Long> userIdList = accountService.queryAllUserId();
		campaignService.deleteAllCampaign(userIdList);
		adgroupService.deleteAllAdgroup(userIdList);
		keywordService.deleteAllKeyword(userIdList);

		for (long userId : userIdList) {
			logger.info("用户:" + userId);
			String refreshToken = accountController.getRefreshToken(userId);
			JSONObject jsonObject = accountController
					.getAccessTokenByRF(refreshToken);

			String accessToken = jsonObject.getString("access_token");
			String newRefreshToken = jsonObject.getString("refresh_token");
			if (newRefreshToken == null) {
				logger.info(userId + "获取rf失败");
				continue;
			}
			accountController.updateRefreshToken(userId, newRefreshToken);
			List<Long> campaignIdList = campaignController.saveAllCampaign(
					accessToken, userId);
			if (campaignIdList == null) {
				logger.info(userId + "获取计划数据失败");
				continue;
			}
			if (!campaignIdList.isEmpty()) {
				List<Long> adgroupIdList = adgroupController.saveAllAdgroup(
						accessToken, campaignIdList, userId);
				if (adgroupIdList == null) {
					logger.info(userId + "获取单元数据失败");
					continue;
				}
				if (!adgroupIdList.isEmpty()) {
					List<KeywordTypeInfo> list = keywordController
							.saveAllKeyword(accessToken, adgroupIdList, userId);
					if (list == null) {
						logger.info(userId + "获取关键词数据失败");
						continue;
					}
				}
			}
		}
		Date end = new Date();
		logger.info("end schedule" + sdf.format(end));
		return null;
	}

	@RequestMapping("/test")
	public List<KeywordTypeInfo> test3(
			@RequestParam Map<String, Object> params, HttpServletRequest request) {
		logger.info("测试开始");
		long userId = 6255867;
		System.out.println(userId);

		String refreshToken = accountController.getRefreshToken(userId);
		JSONObject jsonObject = accountController
				.getAccessTokenByRF(refreshToken);
		
		if (jsonObject==null||jsonObject.getString("access_token") == null) {
			return null;
		}
		String accessToken = jsonObject.getString("access_token");
		String newRefreshToken = jsonObject.getString("refresh_token");
		logger.info(newRefreshToken);
		accountController.updateRefreshToken(userId, newRefreshToken);
		List<Long> userIdList = new ArrayList<Long>();
		userIdList.add(userId);
		campaignService.deleteAllCampaign(userIdList);
		adgroupService.deleteAllAdgroup(userIdList);
		keywordService.deleteAllKeyword(userIdList);
		List<Long> campaignIdList = campaignController.saveAllCampaign(
				accessToken, userId);
		if (campaignIdList == null) {
			logger.info(userId + "获取计划数据失败");
			return null;
		}
		if (!campaignIdList.isEmpty()) {
			List<Long> adgroupIdList = adgroupController.saveAllAdgroup(
					accessToken, campaignIdList, userId);
			if (adgroupIdList == null) {
				logger.info(userId + "获取单元数据失败");
				return null;
			}
			if (!adgroupIdList.isEmpty()) {
				List<KeywordTypeInfo> list = keywordController.saveAllKeyword(
						accessToken, adgroupIdList, userId);
				if (list == null) {
					logger.info(userId + "获取关键词数据失败");
					return null;
				}
			}
		}
		logger.info("测试成功");
		return null;

	}
	@RequestMapping("/sectionalization")
	public R sectionalization(@RequestParam Map<String, Object> params,HttpServletRequest request){
		String industryId = (String) params.get("industryId");
		String keywordstr = (String) params.get("keywordstr");
		String inversestr = (String) params.get("inversestr");
		if(industryId==null||keywordstr==null){
			return R.ok().put("result", "error");
		}
		HttpSession session = request.getSession();
		session.setAttribute("industryId", industryId);
		session.setAttribute("keywordstr", keywordstr);
		session.setAttribute("inversestr", inversestr);
		return R.ok().put("result", "success");
		
	}
	@RequestMapping("/generalizeSet")
	public R generalizeSet(@RequestParam Map<String, Object> params,HttpServletRequest request){
		String promotionPlanName = (String) params.get("promotionPlanName");
		String promotionUnitName = (String) params.get("promotionUnitName");
		String keyword = (String) params.get("keyword");
		String clickRate = (String) params.get("clickRate");
		if(promotionPlanName==null||promotionUnitName==null||keyword==null||clickRate==null){
			return R.ok().put("result", "error");
		}
		HttpSession session = request.getSession();
		session.setAttribute("promotionPlanName", promotionPlanName);
		session.setAttribute("promotionUnitName", promotionUnitName);
		session.setAttribute("keyword", keyword);
		session.setAttribute("clickRate", clickRate);
		return R.ok().put("result", "success");
		
	}

}
